var express = require('express');
var router = express.Router();
var dbconnect=require('../models/dbconnect.js')
/* GET home page. */
var imgul=null;
router.get('/', function(req, res, next) {
  //先查询文章再进行渲染
  //列表分页操作
  var pageNum=1//获取页码
  var pageSize=5//每页显示的数据
  console.log(req.query.num)
  if(req.query.num){
    pageNum=parseInt(req.query.num)
  }
  dbconnect('article').then(function({coll,dbCon}){
    coll.find({},{
      skip:(pageNum-1)*pageSize,
      limit:pageSize
    }).sort({"_id":-1}).toArray(function(error,data){
      console.log(data.length)
      res.render('index', {
        title: '的个人博客',
        hello:'<h1> hello world </h1>',
       username:req.session.username,
        data:data,
        pageNum:pageNum,
        lastPage:data.length,
         Imgurl:imgul

        });
    })
  }).catch(function(error){
    if(error) throw error;
  })
  
});

//查询管理员表如果能查到可以后台登录否则不可以
router.post('/isAdmin',function(req,res){
  dbconnect('Administrators').then(function({coll,dbCon}){
    coll.find({'username':req.session.username}).toArray(function(error,data){
      if(error) throw error;
      if(data.length>0){
        res.json({
          code:1
        })
      }else{
        res.json({
          code:0
        })
      }

    })
  })
})


// 上传头像图片
var multer = require('multer');//安装模块
// var upload = multer({ dest: 'public/images/headimage' });

var storage = multer.diskStorage({
  //路径
  destination: function (req, file, cb) {
   cb(null, 'public/images/headimage')
  },
  filename: function (req, file, cb) {
  //文件名字
   cb(null, file.fieldname + '-' + Date.now()+'.jpg')
  }
})
var upload = multer({ storage: storage })

//上传的post 请求
router.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file 是 `avatar` 文件的信息
            // res.json({code:1,url:req.file.destination+'/'+req.file.filename})
            var url= req.file.destination+'/'+req.file.filename
            console.log(url)
            var imgurl=url.slice(7);
            imgul=imgurl
            console.log(imgurl)
            // res.render('index', {
            //   Imgurl:imgurl
              
      
            //   });
            res.redirect('/')
              
  })




module.exports = router;
